package com.eeplat.social.openapi.http;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.eeplat.social.openapi.qq.URIUtilQQ;
import com.eeplat.social.openapi.renren.AuthRenRen;
import com.eeplat.social.openapi.t360.Auth360;

public class AuthUtil {

	private URIUtil uriUtil;
	
	private ObjectMapper objectMapper = new ObjectMapper();
	
	public AuthUtil(URIUtil util) {
		this.uriUtil = util;
	}

	public String getAccessToken(String oauth_code) throws OpenApiException {

		String authUri = uriUtil.wrappAuthCodeUri(oauth_code);

		HttpClient http = new HttpClient();
		Response res;
		try {
			res = http.httpRequest(authUri,null,"GET");
			String ret = res.asString();
			Map<String, Object> data = objectMapper.readValue(ret, Map.class);
			return (String) data.get("access_token");			
		} catch (Exception e) {
			throw new OpenApiException(e);
		} 
	}

	/**
	 * 使用Access Token来获取用户的OpenID
	 * 
	 * @param accessToken
	 * @return
	 * @throws OpenApiException
	 */
	public String getOpenID(String accessToken) throws OpenApiException {

		String getOpenIdUri = uriUtil.wrappAccessTokenUri(accessToken);
		HttpClient http = new HttpClient();

		Map<String, Object> data;
		try {
			Response res = http.httpRequest(getOpenIdUri,null,"GET");
			String ret = res.asString();
			// callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} );
			data = objectMapper.readValue(ret, Map.class);
			return (String) data.get("openid");
		} catch (Exception e) {
			throw new OpenApiException(e);
		}
	}

	/**
	 * 获取到用户数据
	 * 
	 * @param accessToken
	 * @return
	 * @throws OpenApiException
	 */
	public Map<String, Object> getUserInfo(String accessToken, String openid)
			throws OpenApiException {

		String getOpenIdUri = uriUtil.wrappGetUserInfoUri(accessToken, openid);
		HttpClient http = new HttpClient();

		try {
			Response res = http.httpRequest(getOpenIdUri,null,"GET");
			String ret = res.asString();
			return objectMapper.readValue(ret, Map.class);
		} catch (Exception e) {
			throw new OpenApiException(e);
		}
	}

	public Map<String, Object> getUserInfo(String oauthCode)
			throws OpenApiException {
		String accessToken = this.getAccessToken(oauthCode);
		String openid = this.getOpenID(accessToken);
		return this.getUserInfo(accessToken, openid);
	}

}
